package com.coding.mybatis;

import lombok.Getter;
import lombok.Setter;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ParameterMappingTokenHandler
 * @Author ykx
 * @Date 2023/12/31 16:23
 * @Version 1.0
 */
@Getter
@Setter
public class ParameterMappingTokenHandler {
    /**
     * parameterMappings
     */
    private List<ParameterMapping> parameterMappings = new ArrayList<>();

    /**
     * mappedStatement
     */
    private MappedStatement mappedStatement;

    /**
     * 构造函数
     *
     * @param mappedStatement mappedStatement
     */
    public ParameterMappingTokenHandler(MappedStatement mappedStatement) {
        this.mappedStatement = mappedStatement;
    }

    public String handleToken(String content) {
        parameterMappings.add(buildParameterMapping(content));
        return "?";
    }

    private ParameterMapping buildParameterMapping(String content) {
        ParameterMapping parameterMapping = new ParameterMapping();

        parameterMapping.setName(content);

        Class<?> parameterType = mappedStatement.getParameterType();
        try {
            Field declaredField = parameterType.getDeclaredField(content);
            parameterMapping.setJavaType(declaredField.getType());
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
        return parameterMapping;
    }

}
